package com.itheima.auth.intergration.processor;

import com.itheima.auth.intergration.authenticator.IntegrationAuthenticator;
import com.itheima.auth.intergration.entity.IntegrationAuthenticationEntity;
import com.itheima.common.pojo.Constant;
import com.itheima.common.util.StringUtil;
import com.itheima.sys.client.UserClient;
import com.itheima.sys.dto.SysUserDTO;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;
import springfox.documentation.annotations.ApiIgnore;

@Component
public class SmsAuthenticator implements IntegrationAuthenticator {

    @Autowired
    private UserClient userClient;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 短信验证码认证
     * @param entity 集成认证实体
     * @return
     */
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //1.获取提交手机号参数值
        String mobile = entity.getAuthParameter("mobile");

        //2.暂定验证码值为固定“1234”
        SysUserDTO sysUserDTO = userClient.querUser(mobile).getData();
        if(sysUserDTO==null){
            throw new OAuth2Exception("用户手机号不存在！");
        }
        //3.判断验证码是否匹配
        String password = entity.getAuthParameter("password"); //实际是用户填写验证码

        //获取redis中存放正确验证码
        String realCheckcode = redisTemplate.opsForValue().get(Constant.SMS_LOGIN_KEY_PREFIX + mobile);
        if (realCheckcode.equals(password)) {
            //将验证码作为密码 交给框架比对是否正确（拿着用户提交password验证码值，跟sysUserDTO中加密后验证码值进行比较）
            sysUserDTO.setPassword(passwordEncoder.encode(password));
        }
        return sysUserDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        String authType = entity.getAuthType();
        if(StringUtils.isNotBlank(authType) && authType.equals("sms")){
            return true;
        }
        return false;
    }
}
